package com.youlu.campus.web.linker;

import com.youlu.campus.base.exception.BusinessException;

import com.youlu.campus.entity.ShortUrlConfig;
import com.youlu.campus.service.linker.ShortUrlConfigService;
import com.youlu.campus.service.linker.ShortUrlConfigStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@RestController
public class ShortUrlConfigController {
    @Autowired
    private ShortUrlConfigService shortUrlConfigService;
    @Autowired
    private ShortUrlConfigStatisticsService shortUrlConfigStatisticsService;

    @RequestMapping("/public/s-url/{shortUrl}")
    public void shortUrl(@PathVariable("shortUrl") String shortUrl, HttpServletResponse response) {
        ShortUrlConfig linkerInfo = shortUrlConfigService.findByKey(shortUrl);
        if (Objects.isNull(linkerInfo)) {
            log.error(":>>> 短链接:{} 不存在", shortUrl);
            throw new BusinessException("非法请求");
        }
        log.info(":>>> 短链接:{} 生成的长链接地址为:{}", shortUrl, linkerInfo.getLongUrl());
        try {
            shortUrlConfigStatisticsService.incShortUrlAndAddConfigStatistics(shortUrl, linkerInfo.getId(), 1L);
            log.info(":>>> 短链接:{} 对应的长链接:{}", shortUrl, linkerInfo.getLongUrl());
            response.sendRedirect(linkerInfo.getLongUrl());
        } catch (Exception e) {
            log.error(":>>> 短链接地址错误:{}", e);

        }

    }
}
